package com.example.music_player

import com.example.music_player.MusicService
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.ServiceConnection
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.documentfile.provider.DocumentFile
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlin.random.Random
import android.provider.MediaStore
import android.content.ContentUris
import android.content.pm.PackageManager
import android.os.Build

// UserActivity: 音乐播放器的主界面，负责显示音乐列表和基本播放控制

class UserActivity : AppCompatActivity(), MusicService.OnPlaybackStateChangeListener {

    // 界面组件
    private lateinit var recyclerView: RecyclerView          // 音乐列表视图
    private lateinit var musicAdapter: MusicAdapter          // 音乐列表适配器
    private lateinit var tvPlayingSong: TextView            // 当前播放歌曲名称显示
    private lateinit var folderPathEditText: EditText       // 文件夹路径输入框
    private lateinit var btnMusic: Button                   // 音乐页面按钮
    private lateinit var btnMy: Button                      // 个人页面按钮
    private lateinit var selectFolderButton: Button         // 选择文件夹按钮
    private lateinit var playPauseButton: ImageButton       // 播放/暂停按钮
    private val musicFiles = mutableListOf<MusicFile>()     // 音乐文件列表
    private var musicService: MusicService? = null          // 音乐服务
    private var bound = false                               // 服务绑定状态

    // 文件夹选择器启动器
    private lateinit var folderPickerLauncher: ActivityResultLauncher<Uri?>

    // 服务连接回调
    private val connection = object : ServiceConnection {
        // 服务连接成功
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val binder = service as MusicService.MusicBinder
            musicService = binder.getService()
            bound = true
            musicService?.setMusicList(musicFiles)
            musicService?.addPlaybackStateChangeListener(this@UserActivity)
        }
        
        // 服务断开连接
        override fun onServiceDisconnected(name: ComponentName?) {
            musicService?.removePlaybackStateChangeListener(this@UserActivity)
            musicService = null
            bound = false
        }
    }

    // 权限请求启动器
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        if (permissions.all { it.value }) {
            loadMusicFiles()
        } else {
            Toast.makeText(this, "需要存储权限才能访问音乐文件", Toast.LENGTH_LONG).show()
        }
    }

    // 文件夹变更广播接收器
    private val folderChangeReceiver = object : android.content.BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == "com.example.music_player.FOLDER_CHANGED") {
                val uriString = intent.getStringExtra("folder_uri")
                uriString?.let {
                    try {
                        val uri = Uri.parse(it)
                        saveFolderPathAndLoadMusic(uri)
                    } catch (e: Exception) {
                        Log.e(TAG, "文件夹更改处理失败", e)
                        Toast.makeText(context, "更新文件夹失败", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user)

        // 初始化控件
        folderPathEditText = findViewById(R.id.et_folder_path)
        selectFolderButton = findViewById(R.id.btn_select_folder)
        recyclerView = findViewById(R.id.recycler_view_music)
        recyclerView.layoutManager = LinearLayoutManager(this)
        tvPlayingSong = findViewById(R.id.tv_playing_song)
        tvPlayingSong.isSelected = true
        tvPlayingSong.requestFocus()
        playPauseButton = findViewById(R.id.btn_play_pause)
        btnMusic = findViewById(R.id.btn_music)
        btnMy = findViewById(R.id.btn_my)

        musicAdapter = MusicAdapter(musicFiles, this)
        recyclerView.adapter = musicAdapter

        // 隐藏文件选择相关控件
        folderPathEditText.visibility = View.GONE
        selectFolderButton.visibility = View.GONE

        // 尝试加载当前账号保存的文件夹路径
        loadSavedFolderPath()

        // 检查并请求权限
        checkAndRequestPermissions()

        // 启动并绑定服务
        Intent(this, MusicService::class.java).also { intent ->
            bindService(intent, connection, Context.BIND_AUTO_CREATE)
            startService(intent)
        }

        // 修改播放按钮点击事件
        playPauseButton.setOnClickListener {
            if (musicService?.isPlaying() == true) {
                musicService?.pauseMusic()
                playPauseButton.setImageResource(R.drawable.ic_play)
            } else {
                if (musicService?.getCurrentPosition() ?: 0 > 0) {
                    musicService?.resumeMusic()
                } else {
                    musicFiles.firstOrNull()?.let { firstMusic ->
                        musicService?.playMusic(firstMusic.uri)
                    }
                }
                playPauseButton.setImageResource(R.drawable.ic_pause)
            }
        }

        btnMusic.setOnClickListener {
            Toast.makeText(this, "已在音乐界面", Toast.LENGTH_SHORT).show()
        }

        btnMy.setOnClickListener {
            val intent = Intent(this, UserProfileActivity::class.java)
            startActivity(intent)
        }

        folderPickerLauncher = registerForActivityResult(
            ActivityResultContracts.OpenDocumentTree()
        ) { uri: Uri? ->
            uri?.let {
                saveFolderPathAndLoadMusic(it)
            }
        }

        selectFolderButton.setOnClickListener {
            openFolderPicker()
        }

        // 添加播放状态栏的点击事件
        findViewById<LinearLayout>(R.id.bottom_player_bar).setOnClickListener {
            val intent = Intent(this, PlayerActivity::class.java)
            startActivity(intent)
        }

        // 修改广播接收器的注册
        val filter = IntentFilter("com.example.music_player.FOLDER_CHANGED")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(
                folderChangeReceiver,
                filter,
                Context.RECEIVER_NOT_EXPORTED
            )
        } else {
            registerReceiver(folderChangeReceiver, filter)
        }
    }

    private fun openFolderPicker() {
        folderPickerLauncher.launch(null)
    }

    private fun loadSavedFolderPath() {
        try {
            val currentUsername = getCurrentUsername()
            val savedPath = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
                .getString(KEY_FOLDER_PATH_PREFIX + currentUsername, null)

            if (savedPath != null) {
                val uri = Uri.parse(savedPath)
                val hasPermission = contentResolver.persistedUriPermissions.any { 
                    it.uri == uri && it.isReadPermission 
                }

                if (hasPermission) {
                    loadMusicFilesFromFolder(uri)
                } else {
                    // 如果没有权限，清除保存的路径并使用默认加载方式
                    clearSavedPath(currentUsername)
                    loadMusicFiles()
                }
            } else {
                loadMusicFiles()
            }
        } catch (e: Exception) {
            Log.e(TAG, "加载保存的路径失败: ${e.message}")
            loadMusicFiles()
        }
    }

    private fun clearSavedPath(username: String) {
        getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
            .edit()
            .remove(KEY_FOLDER_PATH_PREFIX + username)
            .commit()
    }

    private fun saveFolderPathAndLoadMusic(uri: Uri) {
        try {
            val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or
                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION
            
            // 释放之前的所有权限
            contentResolver.persistedUriPermissions.forEach { permission ->
                try {
                    contentResolver.releasePersistableUriPermission(
                        permission.uri,
                        Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                    )
                } catch (e: Exception) {
                    Log.e(TAG, "释放权限失败: ${e.message}")
                }
            }

            // 获取新的权限
            contentResolver.takePersistableUriPermission(uri, takeFlags)

            // 验证权限
            val hasPermission = contentResolver.persistedUriPermissions.any { 
                it.uri == uri && it.isReadPermission 
            }

            if (hasPermission) {
                // 保存路径
                val currentUsername = getCurrentUsername()
                getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit().apply {
                    putString(KEY_FOLDER_PATH_PREFIX + currentUsername, uri.toString())
                    commit()  // 使用 commit 确保立即保存
                }

                // 加载音乐
                loadMusicFilesFromFolder(uri)
            } else {
                throw SecurityException("无法获取文件夹访问权限")
            }
        } catch (e: Exception) {
            Log.e(TAG, "保存文件夹路径失败: ${e.message}")
            Toast.makeText(this, "无法访问选择的文件夹，请重试", Toast.LENGTH_SHORT).show()
            loadMusicFiles() // 回退到默认加载方式
        }
    }

    private fun loadMusicFilesFromFolder(uri: Uri) {
        val fileList = mutableListOf<MusicFile>()
        val documentFile = DocumentFile.fromTreeUri(this, uri)
        val likedMusicSet = getSharedPreferences("UserPreferences", Context.MODE_PRIVATE)
            .getStringSet("likedMusic", emptySet()) ?: emptySet()

        documentFile?.let {
            for (file in it.listFiles()) {
                if (file.isFile && file.type?.startsWith("audio/") == true) {
                    val musicFile = MusicFile(name = file.name ?: "未知文件", uri = file.uri)
                    fileList.add(musicFile)
                }
            }
        }

        if (fileList.isNotEmpty()) {
            musicFiles.clear()
            musicFiles.addAll(fileList)
            // 按喜欢状态排序
            musicFiles.sortByDescending { likedMusicSet.contains(it.uri.toString()) }
            musicAdapter.notifyDataSetChanged()
        } else {
            Toast.makeText(this, "未找到音乐文件，切换到默认模式", Toast.LENGTH_SHORT).show()
            loadMusicFiles()
        }
    }

    private fun getCurrentUsername(): String {
        val sharedPreferences = getSharedPreferences("UserPreferences", MODE_PRIVATE)
        return sharedPreferences.getString("currentUsername", "defaultUser") ?: "defaultUser"
    }

    private fun recordMusicHistory(musicFile: MusicFile) {
        val currentUsername = getCurrentUsername() // 获取当前登录用户名
        val sharedPreferences = getSharedPreferences("MusicHistory", Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        val currentTime = System.currentTimeMillis()
        val historyEntry = "${musicFile.uri},$currentTime"

        val userHistoryKey = "history_$currentUsername" // 使用用户名作为前
        val historyList = sharedPreferences.getStringSet(userHistoryKey, mutableSetOf())?.toMutableSet() ?: mutableSetOf()
        historyList.add(historyEntry)

        editor.putStringSet(userHistoryKey, historyList)
        editor.apply()
    }

    fun playMusicAtPosition(position: Int) {
        musicService?.let { service ->
            service.setMusicList(musicFiles)
            service.playMusicAtPosition(position)
            playPauseButton.setImageResource(R.drawable.ic_pause)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun updateMusicList() {
        val likedMusicSet = getSharedPreferences("UserPreferences", Context.MODE_PRIVATE)
            .getStringSet("likedMusic", emptySet()) ?: emptySet()
        
        // 按喜欢状态排序
        musicFiles.sortByDescending { likedMusicSet.contains(it.uri.toString()) }
        musicAdapter.notifyDataSetChanged()
    }

    override fun onDestroy() {
        super.onDestroy()
        musicService?.removePlaybackStateChangeListener(this)
        if (bound) {
            unbindService(connection)
            bound = false
        }
        // 注销广播接收器
        unregisterReceiver(folderChangeReceiver)
    }

    // 加载音乐文件列表
    private fun loadMusicFiles() {
        val musicList = mutableListOf<MusicFile>()
        val collection = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI

        val projection = arrayOf(
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.DISPLAY_NAME,
            MediaStore.Audio.Media.DURATION
        )

        // 只选择音乐文件
        val selection = "${MediaStore.Audio.Media.IS_MUSIC} != 0"
        
        // 按名称排序
        val sortOrder = "${MediaStore.Audio.Media.DISPLAY_NAME} ASC"

        // 查询媒体库获取音乐文件
        contentResolver.query(
            collection,
            projection,
            selection,
            null,
            sortOrder
        )?.use { cursor ->
            val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)
            val nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)

            while (cursor.moveToNext()) {
                val id = cursor.getLong(idColumn)
                val name = cursor.getString(nameColumn)

                val contentUri = ContentUris.withAppendedId(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    id
                )

                val musicFile = MusicFile(name = name, uri = contentUri)
                musicList.add(musicFile)
            }
        }

        // 获取喜欢的音乐列表并排序
        val likedMusicSet = getSharedPreferences("UserPreferences", MODE_PRIVATE)
            .getStringSet("likedMusic", emptySet()) ?: emptySet()

        // 将喜欢的音乐排在前面
        musicList.sortByDescending { likedMusicSet.contains(it.uri.toString()) }

        // 更新列表
        musicFiles.clear()
        musicFiles.addAll(musicList)
        musicAdapter.notifyDataSetChanged()
    }

    private fun checkAndRequestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13 及以上使用新的权限
            if (checkSelfPermission(android.Manifest.permission.READ_MEDIA_AUDIO) 
                != PackageManager.PERMISSION_GRANTED) {
                requestPermissionLauncher.launch(arrayOf(
                    android.Manifest.permission.READ_MEDIA_AUDIO
                ))
            } else {
                loadMusicFiles()
            }
        } else {
            // Android 12 及以下使用旧的存储权限
            if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) 
                != PackageManager.PERMISSION_GRANTED) {
                requestPermissionLauncher.launch(arrayOf(
                    android.Manifest.permission.READ_EXTERNAL_STORAGE
                ))
            } else {
                loadMusicFiles()
            }
        }
    }

    // 播放状态回调实现
    override fun onSongChanged(songName: String?) {
        tvPlayingSong.text = songName ?: "暂无播放"
    }

    override fun onPlayStateChanged(isPlaying: Boolean) {
        playPauseButton.setImageResource(
            if (isPlaying) R.drawable.ic_pause else R.drawable.ic_play
        )
    }

    companion object {
        private const val TAG = "UserActivity"                    // 日志标签
        private const val PREFS_NAME = "MusicFolderPrefs"        // 偏好设置名称
        private const val KEY_FOLDER_PATH_PREFIX = "folder_path_" // 文件夹路径键前缀
    }

    // 添加一个处理无效路径的辅助函数
    private fun handleInvalidPath(username: String) {
        Toast.makeText(this, "需要重新选择音乐文件夹", Toast.LENGTH_LONG).show()
        // 清除所有相关的存储
        getSharedPreferences("UserPreferences", MODE_PRIVATE).edit()
            .remove("lastFolderPath_$username")
            .remove("lastFolderPathTimestamp_$username")
            .apply()
        getSharedPreferences("FolderPathBackup", MODE_PRIVATE).edit()
            .remove("path_$username")
            .apply()
        loadMusicFiles()
    }

}